<template>
	<tr class="data-table-item">
		<td class="data-name-wrapper">
            <input type="text" class="data-name-input"
                v-show='editName'
                v-model="dataName"
                @blur="stopEdit"
                @input="validation"
                :id="data.uid"
                v-on:keyup.enter="stopEdit"
                maxlength="50"
                >
            <div class="data-name" v-show="!editName"  @click="startEdit(data.uid)">
                {{dataName}}
                <span v-if="isPrivate" class="iconfont icon-editor editor" title="重命名"></span>
            </div>
        </td>
		<td class="data-count">{{data.count}}</td>
		<td class="data-time">{{data.updatedAt | timeFormat}}</td>
		<td class="data-action">
			 <div class="data-option">

	            <div class="chain" >
	                <i class="iconfont icon-menu large" @click="toggleMenu('menu')" @blur="closeMenu" tabindex="-1"></i>

	                <!--注意，通过toggleMenu控制的菜单，其内部的所有点击事件一定要使用onmousedown来触发，否则blur事件会先于click执行-->
	                <div class="chain-option-container"  :class="{'is-private':isPrivate}" v-show="currentMenu === uid+'_menu'">
	                    <div @mousedown="dataPreview">
	                        <div class="option-icon"><i class="iconfont icon-eye"></i></div>
	                         数据预览
	                    </div>
	                    <div v-if="isPrivate" @mousedown="openWithDataEditor" target="_blank">
	                        <div class="option-icon"><i class="iconfont icon-data-editor"></i></div>
	                         数据编辑
	                    </div>
	                    <div @mousedown="openWithDataViz" target="_blank">
	                        <div class="option-icon"><i class="iconfont icon-dataviz"></i></div>
	                         数据上图
	                    </div>
	                   <!--  <div onmousedown="window.open('apps/dataviz3d')" target="_blank">
	                        <div class="option-icon"><i class="iconfont icon-dataviz3d"></i></div>
	                         三维数据上图
	                    </div> -->
	                    <div  v-if="isPrivate" class="delete" @mousedown="removeData()">
	                        <div class="option-icon"><i class="iconfont icon-delete"></i></div>
	                         删除数据
	                    </div>
	                </div>
	            </div>

	            <template v-if="isPrivate">
	                <div class="download" >
	                    <i v-if="!prepareing" class="iconfont icon-download large" @click="toggleMenu('download')" @blur="closeMenu" tabindex="-1"></i>
	                    <i v-else class="iconfont icon-loading large icon-spin"></i>

	                    <div class="download-option-container" v-show="currentMenu === uid+'_download'">
	                        <div v-show="data.convertEnd" class="shapefile-download">
	                            <div>下载SHP</div>
	                            <div class="shp-sub-option-container-wrapper">
	                                <div class="shp-sub-option-container">
	                                    <div v-if="showWgs84DownloadOption" @mousedown="download('shp', 'wgs')">WGS84</div>
	                                    <div @mousedown="download('shp', 'bd')">百度坐标</div>
	                                    <div @mousedown="download('shp', 'gcj02')">高德坐标</div>
	                                </div>
	                            </div>
	                        </div>
	                        <div class="csv-download">
	                             <div @mousedown="download('csv', 'gcj02')">下载CSV</div>
	                             <div class="csv-sub-option-container-wrapper" v-if="this.data.geometryType === 'pt'">
	                                <div class="csv-sub-option-container">
	                                    <div v-if="showWgs84DownloadOption" @mousedown="download('csv', 'wgs')">WGS84</div>
	                                    <div @mousedown="download('csv', 'bd')">百度坐标</div>
	                                    <div @mousedown="download('csv', 'gcj02')">高德坐标</div>
	                                </div>
	                             </div>
	                        </div>
	                    </div>
	                </div>

	                <div @click="share" class="share">
	                    <i class="iconfont icon-share large"></i>
	                </div>
	            </template>
	            <div @click="addStar" class="star">
	                <i class="iconfont icon-heart2 large" title="收藏"></i>
	            </div>
	            <div @click="copyUid" class="copy">
	                <i class="iconfont icon-files large" title="复制数据UID"></i>
	            </div>

	        </div>
		</td>
    </tr>
</template>

<script>

import axios from 'axios'
import {publicData as publicAPI} from '@/api'
import {data as dataAPI} from '@/api'
import Clipboard from 'clipboard'

var qs = require('qs');

export default{
	name: 'data-table-item',
	props: {
		data: Object,
		isPrivate: {
        	type: Boolean,
        	default: false
     	},
     	currentMenu: String,
	},
    data(){
       
        let showWgs84DownloadOption = this.$root.showWgs84DownloadOption != undefined ? 
            this.$root.showWgs84DownloadOption : false;
        return {
            editName: false,
            dataName: this.data.name,
            uid: this.data.uid,
            oldName:'',
            prepareing: false,
            refreshing: false,
            showSubOption: false,
            showWgs84DownloadOption:  showWgs84DownloadOption == 'true'
        }
    },
	filters: {
        timeFormat: (value) => {
            var date = new Date(value);
            return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
        }
    },
	methods: {
		 toggleMenu(type) {

            let currentMenu = `${this.uid}_${type}`;

            if (this.currentMenu === currentMenu) {
                this.$emit('set-current-menu', '');
                return;
            }

            this.$emit('set-current-menu', `${this.uid}_${type}`);
        },

        closeMenu() {

            this.$emit('set-current-menu', '');

        },

        dataPreview() {
            this.$emit('data-preview', this.data);
        },

        share() {

            if (!this.data.convertEnd) {
                this.$emit('open-spatializ-warning', this.uid);
                return;
            }
            
            this.$emit('data-share', this.data, this.dataName);

        },

        addStar(){

        },

        copyUid() {
            let button = document.createElement('button');
            let uid = this.uid;

            let clipboard = new Clipboard(button, {
                text: () => {
                    return uid;
                }
            });

            clipboard.on('success', (e) => {
                e.clearSelection();
                this.$message.success('数据uid已复制到剪切板');
                clipboard.destroy();
            });

            clipboard.on('error', (e) => {
                this.$message.error('复制失败')
            });

            button.click();
        },

        openWithDataEditor() {

            if (!this.data.convertEnd) {
                this.$emit('open-spatializ-warning', this.uid);
                return;
            }
            
            window.open(`apps/data-editor/${this.uid}`);
        },

        openWithDataViz() {
            
            if( !this.data.geometryType ){
                this.$emit('data-preview', this.data);
                return;
            }
            if( this.isPrivate ){
                window.open(`apps/dataviz/new?datauid=${this.uid}&datatype=private`);
            }else{
                window.open(`apps/dataviz/new?datauid=${this.uid}&datatype=public`);
            }
        },

        validation(e) {

            let val = this.dataName.replace(/[@#:;\$%\^&\*\\、\+\=<>\[\]\{\}\|?!,，。？'"’”【】\/\~\`]+/g, '');
            this.dataName = val;

        },

        startEdit(id) {
            this.editName = true;

            this.oldName = this.dataName;

            this.$nextTick(function () {
                document.getElementById(id).focus();
            })

        },

        stopEdit() {

            if (this.oldName === this.dataName) {
                this.editName = false;
                return;
            }

            if (this.editName) {
                this.editName = false;
                this.rename();
            }

        },

        rename() {

            let params = {
                name: this.dataName
            }

            let header = {'Content-Type': 'application/x-www-form-urlencoded' };
            axios.post(`s/data/${this.data.uid}/rename`, qs.stringify(params), {headers:header})

                .then((res) => {
                    if (res.data.code !=0) {
                        this.$message.error('数据重命名失败');
                        this.dataName = this.oldName;
                        return;
                    }

                    this.data.name = this.dataName;

                    this.$message.success('数据重命名成功');
                })
                .catch((err) => {
                    this.$message.error('数据重命名失败');
                    this.dataName = this.oldName;
                })
        },

        removeData() {
            this.$emit('data-remove', this.data, this.dataName);
        },

        download (type, srs) {

            this.prepareing = true;

            let header = {'Content-Type': 'application/json'};
            axios.post(`s/data/${this.data.uid}/download/${type}/${srs}`)
                .then((res) => {
                    let code = res.data.code;
                    if (code == 101 || code == 1 || code == 102 || code == 103) {
                        let msg = res.data.msg;

                        if (msg) {
                            this.$message.error(msg);
                        }

                        this.prepareing = false;

                        return;
                    }

                    this.getDownloadStatus(type, srs);

                })
                .catch((err) => {
                    this.$message.error('下载失败');
                    this.prepareing = false;
                })

        },

        getDownloadStatus (type, srs) {
            axios.post(`s/data/${this.data.uid}/download/${type}/${srs}/status`)
                .then((res) => {
                    let code = res.data.code;
                    if (code != 0) {
                        let msg = res.data.msg;

                        if (msg) {
                            this.$message.error(msg);
                        }

                        this.prepareing = false;

                        return;
                    }

                    let data = res.data.data;
                    let status = data.status;

                    if (status === -1) {
                        this.$message.error(data.msg);
                        this.prepareing = false;
                        return;
                    }

                    if (status === 0 || status === 1) {

                        setTimeout(() => {
                            this.getDownloadStatus(type, srs);
                        },3000);

                    }

                    if (status === 2) {
                        this.downloadFile(data.url);
                    }

                })
                .catch((err) => {
                    this.$message.error('下载失败');
                    this.prepareing = false;
                })
        },

        downloadFile(url) {
            let downloadIframe = document.getElementById('downloadIframe');

            if (!downloadIframe) {
                downloadIframe = document.createElement("iframe");
                downloadIframe.id = "downloadIframe";
                downloadIframe.style.display = "none";
            }

            if (url.indexOf('http') === 0) {
                url = url.split(':').slice(1).join('');
            }

            downloadIframe.src = url;

            document.body.appendChild(downloadIframe);

            this.prepareing = false;
        },
	}
}
</script>

<style lang="scss">
    @import "common";
    // .data-table-item{
    //    td{
    //         height: 40px;
    //         font-size: 14px;
    //         text-align: left;
    //         border-bottom:1px solid #e6e9f0;
    //    }
    // }

    // .data-name-wrapper{
    //     padding: 0 8px;

    //     .data-name-input{
    //         border: 1px solid $bdGray;
    //         border-radius: $bdRadius;
    //         width: 100%;
    //         height: 28px !important;
    //         padding: 5px !important;
    //         color: $dark;
    //         font-weight: 400;
    //         font-size: 14px;
    //         border-color: $primary;
    //         @include box-shadow(inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba($primary, .6));
    //     }

    //     .data-name{
    //         @include text-overflow;
    //         height: 22px;
    //         text-align: left;
    //         font-size: 14px;
    //         line-height: 22px;
    //         margin-bottom: 4px;
    //         position: relative;
    //         overflow: hidden;

    //         .editor{
    //             visibility: hidden;
    //             // opacity: 0.6;
    //             margin-top: 2px;
    //             font-size: 20px;
    //             color: #889;
    //             position: absolute;
    //             right: 0;
    //             @include transition(all .3s);
    //         }

    //         &:hover .editor{
    //             visibility: visible;
    //         }

    //     }
    // }

    // .data-action,.data-count, .data-time{
    //     width: 160px;
    // }
    // .data-option{

    //     position: relative;
    //     display: inline-block;
    //     heigth: 40px;

    //     >div{
    //         float: right;
    //         margin-left: 8px;
    //         position:relative;
    //         height: 20px;
    //         width: 20px;
    //         line-height: 20px;


    //         >i{
    //             outline: none;
    //         }

    //     }

    //     .large{
    //         font-size: 20px;
    //     }

    //     .chain {
    //         position: relative;
            
    //         .chain-option-container{
    //             // overflow: hidden;
    //             position: absolute;
    //             z-index: 9;
    //             width: 118px;
    //             background-color: $bgWhite;
    //             border-radius: $bdRadius;
    //             bottom: 21px;
    //             right: -8px;
    //             border: 1px solid $bdGray;

    //             i {
    //                 font-size: 14px;
    //                 width: 18px;
    //             }

    //             >div {
    //                 padding: 4px 6px;
    //                 cursor: pointer;
    //                 white-space: nowrap;

    //                 &:hover{
    //                     background-color: #e8eef6;
    //                 }
    //             }

    //             .delete{
    //                 color: $danger;
    //             }

    //             .option-icon{
    //                 width: 18px;
    //                 text-align: center;
    //                 float: left;
    //                 margin-right: 6px;
    //             }

    //         }

    //         .icon-menu:hover {
    //             font-weight: 500;
    //             color: $primary;
    //         }

    //         .icon-menu:focus {
    //             font-weight: 500;
    //             color: $primary;
    //         }
    //     }

    //     .download {
    //         .download-option-container{
    //             // overflow: hidden;
    //             position: absolute;
    //             z-index: 9;
    //             background-color: $bgWhite;
    //             border-radius: $bdRadius;
    //             bottom: 21px;
    //             left: 40px;
    //             border: 1px solid $bdGray;

    //             .shapefile-download:hover {
    //                 .shp-sub-option-container-wrapper {
    //                     padding: 16px;
    //                     display: block;
    //                 }
    //             }

    //             .csv-download:hover {
    //                 .csv-sub-option-container-wrapper {
    //                     padding: 16px;
    //                     display: block;
    //                 }
    //             }

    //             >div {
    //                 padding: 4px 6px;
    //                 cursor: pointer;
    //                 white-space:nowrap;

    //                 &:hover{
    //                     background-color: #e8eef6;
    //                 }
    //             }
    //         }

    //         .shp-sub-option-container-wrapper {
    //             display: none;
    //             position: absolute;
    //             left: -80px;
    //             top: -16px;
    //             z-index: 99;
    //             .shp-sub-option-container {
    //                 height: auto;
    //                 padding: 6px;
    //                 background-color: #fff;
    //                 border-radius: 4px;
    //                 border: 1px solid #ddd;
    //             }
    //         }

    //         .csv-sub-option-container-wrapper {
    //             z-index: 99;
    //             display: none;
    //             position: absolute;
    //             left: -80px;
    //             top: 10px;
    //             .csv-sub-option-container {
    //                 height: auto;
    //                 padding: 6px;
    //                 background-color: #fff;
    //                 border-radius: 4px;
    //                 border: 1px solid #ddd;
    //             }
    //         }

    //         .icon-loading{
    //             font-size: 16px;
    //             margin-left: 3px;
    //         }

    //         .icon-download:hover {
    //             font-weight: 500;
    //             color: $primary;
    //         }

    //         .icon-download:focus {
    //             font-weight: 500;
    //             color: $primary;
    //         }
    //     }

    //     .share,.copy {
    //         >i:hover {
    //             font-weight: 500;
    //             color: $primary;
    //         }
    //     }
    // }
</style>